//
//  AppDelegate.m
//  TestDemo
//
//  Created by fengxijun on 2/25/16.
//  Copyright © 2016 goappbox. All rights reserved.
//

#import "AppDelegate.h"
#import "TTNavController.h"
#import "ViewController.h"
//#import "MetalViewController.h"
//#import "ApplePayController.h"
#import "NewsstandController.h"
#import "CoreSpotlightTestController.h"
#import <objc/runtime.h>
#import "TestSort.h"

#import "TestSubModel.h"

#import "NSArray+YQJExtesionSignal.h"
#import "TestRACObject.h"

#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>
#import "UIImage+PHA.h"

@interface TestDDD : NSObject
@property (nonatomic, strong) NSMutableString *string1;

@property (nonatomic, strong) const NSMutableString *string2;

@property (nonatomic, strong) NSMutableString * const string3;

@end

@interface AppDelegate ()
{
}
@property (nonatomic,strong)NSMutableArray *racArray;
@end

@interface AppDelegate (PlayingInfoCenter)
- (void)setAudioSession;
@end

@implementation AppDelegate


-(void)testSort
{
    NSTimeInterval tm = [[NSDate date] timeIntervalSince1970];
    TestSort *sort = [[TestSort alloc] init];
    sort.dateTm = @(tm + 3600 * 24 * 31 * 7);
    TestSort *sort1 = [[TestSort alloc] init];
    sort1.dateTm = @(tm + 3600 * 24 * 31 * 5);
    TestSort *sort2 = [[TestSort alloc] init];
    sort2.dateTm = @(tm + 3600 * 24 * 31 * 2);
    TestSort *sort3 = [[TestSort alloc] init];
    sort3.dateTm = @(tm + 3600 * 24 * 31 * 7);
    TestSort *sort4 = [[TestSort alloc] init];
    sort4.dateTm = @(tm - 3600 * 24 * 20);
    
    NSArray *format_array = @[sort,sort1,sort2,sort3,sort4];
    
    NSLog(@"format_array : %@",format_array);
    NSArray *sort_array = [format_array sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"sort_array : %@",sort_array);
    
}

- (void)testModel
{
    TestModel *model = [[TestModel alloc] init];
    [model testRun];
//    [model exchangeMethod];
}

- (void)scaleImages
{
    
//    NSArray *imageNames = @[@"example1.jpg"];
    UIImage *image = [UIImage imageNamed:@"example1.jpg"];
    NSString *hashCode = [image imageFingerPrint];
    NSLog(@"hashCode : %@",hashCode);
    
//    for (NSString *name in imageNames) {
//        NSLog(@"name : %@",name);
//        
//        NSLog(@"=====");
//        
//    }
    
//    NSString * a = @"afcd359";
//    for (NSInteger i = 0; i < [a length]; i++) {
//        printf("%c\n",[a characterAtIndex:i]);
//    }
    
//    NSArray *imageNames = @[@"example1.jpg",@"example2.jpg",@"example3.jpg",@"example4.jpg",@"example5.jpg",@"example6.jpg"];
//    for (NSString *name in imageNames) {
//        UIImage *image = [UIImage imageNamed:name];
//        UIImage *scaleImage = [image grayImage64];
//        NSString *filepath = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:name] stringByAppendingPathExtension:@"jpg"];
//        NSLog(@"%@",filepath);
//        NSLog(@"save success : %@",[UIImageJPEGRepresentation(scaleImage, 1.0) writeToFile:filepath atomically:YES] ? @"YES" : @"NO");
//    }
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
//    [self setAudioSession];
//    [self testModel];
    
//    [self scaleImages];
    
    // Override point for customization after application launch.
//    self.window = [[TTWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
//    //    ViewController *controller = [[ViewController alloc] init];
//    //    TTNavController *nav = [[TTNavController alloc] initWithRootViewController:controller];
//    //    self.window.rootViewController = nav;
//    
//    NewsstandController *controller = [[NewsstandController alloc] init];
//    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:controller];
//    [self.window makeKeyAndVisible];
    
    //    NSArray *keys = [[NSArray arrayWithObjects:@(0),@(4),@(3),@(2),@(5),@(11),@(10001),@(12),@(10),@(19), nil] sortedArrayUsingSelector:@selector(compare:)];
    //    NSLog(@"%@",keys);
    //    for (NSInteger i = 0; i < 10; i++) {
    //        [self exhange];
    //        sleep(10);
    //    }
//    [self testSort];
    
//    [self testRACSequence];
    
//    [self testKVCKVO];
    
    return YES;
}

-(void)exhange
{
    NSString *pkgIdFromTimestamp= [self pkgIdFromTimestamp];
    NSLog(@"pkgIdFromTimestamp : %@",pkgIdFromTimestamp);
    NSData *stringToHexData = [self stringToHexData:pkgIdFromTimestamp];
    NSString *dataToHexString = [self dataToHexString:stringToHexData];
    NSLog(@"dataToHexString : %@",dataToHexString);
    uint64_t endS = strtoull([dataToHexString UTF8String], NULL, 16);
    NSLog(@"endS : %llu",endS);
    NSLog(@"endS Date Time : %@",[self localDateTimeWithFormatString:@"HH:mm" date:[NSDate dateWithTimeIntervalSince1970:endS / 1000.f]]);
}

-(NSString *)localDateTimeWithFormatString:(NSString *)formatString date:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatString];
    NSString *localDateString = [dateFormatter stringFromDate:date];
    return localDateString;
}

-(NSString *)pkgIdFromTimestamp
{
    @autoreleasepool {
        NSLog(@"localData : %@",[self localDateTimeWithFormatString:@"yyyy-MM-dd'T'HH:mm:ssZ" date:[NSDate date]]);
        uint64_t time = (uint64_t)([[NSDate date] timeIntervalSince1970] * 1000);
        NSLog(@"time : %llu",time);
        return [NSString stringWithFormat:@"%016llx",time];
    }
}

- (NSData *) stringToHexData:(NSString *)hexString
{
    NSUInteger len = [hexString length] / 2;    // Target length
    unsigned char *buf = malloc(len);
    unsigned char *whole_byte = buf;
    char byte_chars[3] = {'\0','\0','\0'};
    
    int i;
    for (i=0; i < [hexString length] / 2; i++) {
        byte_chars[0] = [hexString characterAtIndex:i*2];
        byte_chars[1] = [hexString characterAtIndex:i*2+1];
        *whole_byte = strtol(byte_chars, NULL, 16);
        whole_byte++;
    }
    
    NSData *data = [NSData dataWithBytes:buf length:len];
    free( buf );
    return data;
}

- (NSString *) dataToHexString:(NSData *)data
{
    NSUInteger          len = [data length];
    char *              chars = (char *)[data bytes];
    NSMutableString *   hexString = [[NSMutableString alloc] init];
    
    for(NSUInteger i = 0; i < len; i++ )
        [hexString appendString:[NSString stringWithFormat:@"%0.2hhx", chars[i]]];
    
    return hexString;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.goappbox.TouchTest" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TouchTest" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"TouchTest.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

- (BOOL)application:(UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray * _Nullable))restorationHandler
{
    NSString *idetifier = userActivity.userInfo[@"kCSSearchableItemActivityIdentifier"];
    
    UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
    
    [navigationController popToRootViewControllerAnimated:YES];
    
    CoreSpotlightTestController *coreViewController = [[navigationController viewControllers] firstObject];
    
    [coreViewController showViewControllerWithIdentifier:idetifier];
    
    return YES;
}

- (void)testKVCKVO
{
    NSTimeInterval tm = 0.f;
    TestSort *sort = [[TestSort alloc] init];
    sort.dateTm = @(tm + 3600 * 24 * 31 * 7);
    TestSort *sort1 = [[TestSort alloc] init];
    sort1.dateTm = @(tm + 3600 * 24 * 31 * 5);
//    NSArray *array = [NSArray arrayWithObjects:@"Hello", @"Welcome", nil];
//    NSUInteger length = [[array valueForKeyPath:@"@sum.length"] integerValue];
    NSArray *array = [NSArray arrayWithObjects:sort, sort1, nil];
    double length = [[array valueForKeyPath:@"@sum.dateTm"] doubleValue];
//    for (id value in resultArray) {
//        NSLog(@"type : %@",[[value class] description]);
//    }
    NSLog(@"length : %lf", length);
}

- (void)testRACSequence
{
//    const NSString *t = @"test";
//    NSLog(@"test %p : %p : %@",&t,t,t);
//    t = @"welcome";
//    NSLog(@"test %p : %p : %@",&t,t,t);
//    
//    NSString const* t1 = @"Hello";
//    NSLog(@"test %p : %p : %@",&t1,t1,t1);
//    t1 = t;
//    NSLog(@"test %p : %p : %@",&t1,t1,t1);
//    
//    NSString * const t2 = @"const";
//    NSLog(@"test %p : %p : %@",&t2,t2,t2);
    
//    const int int_t = 5;
//    int_t = 5;
//    int const int_t1 = 4;
//    int_t1 = 5;
    
    const TestDDD *obj = [[TestDDD alloc] init];
    
//    TestDDD const *obj1 = [[TestDDD alloc] init];
//    
//    TestDDD * const obj2 = [[TestDDD alloc] init];
    
//    obj.string1 = [[NSMutableString alloc] init];
//    obj.string2 = [[NSMutableString alloc] init];
//    obj.string3 = [[NSMutableString alloc] init];
//    
//    *obj.string2 = &obj.string2;
//
//    obj.string1 = test1;
//    obj.string2 = test2;
//    obj.string1 = test2;
//    obj.string2 = test1;
    
//    obj.string1 = @"Hello";
//    obj.string2 = @"Welcome";
//    NSLog(@"str : %p : %p",obj.string1, obj.string2);
//    obj.string1 = @"你好";
//    obj.string2 = @"欢迎";
//    NSLog(@"str : %p : %p",obj.string1, obj.string2);
    
    
//    obj1.obj = @"DDDD";
//    obj2.obj = @"welcome";
    
}

@end

@implementation TestDDD

@end

//@implementation AppDelegate (PlayingInfoCenter)
//
//- (void)configNowPlayingInfoCenter:(id)mediaInfo {
//    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
//    [dict setObject:@"name" forKey:MPMediaItemPropertyTitle];
//    [dict setObject:@"singer" forKey:MPMediaItemPropertyArtist];
//    [dict setObject:@"album" forKey:MPMediaItemPropertyAlbumTitle];
//    
//    UIImage *image = [UIImage imageNamed:@"test.jpg"];
//    MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
//    [dict setObject:artwork forKey:MPMediaItemPropertyArtwork];
//    
//    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
//}
//
//-(void)viewDidAppear:(BOOL)animated{
//    
//    //Once the view has loaded then we can register to begin recieving controls and we can become the first responder
//    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
//    [self becomeFirstResponder];
//    
//    [self configNowPlayingInfoCenter:nil];
//    
//}
//
//-(void)viewWillDisappear:(BOOL)animated{
//    
//    //End recieving events
//    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
//    [self resignFirstResponder];
//    
//}
//
//-(void)remoteControlReceivedWithEvent:(UIEvent *)event{
//    
//    //if it is a remote control event handle it correctly
//    if (event.type == UIEventTypeRemoteControl) {
//        switch (event.subtype) {
//            case UIEventSubtypeRemoteControlTogglePlayPause:
//            {
//                NSLog(@"UIEventSubtypeRemoteControlTogglePlayPause...");
////                [self pauseOrPlay];
//                break;
//            }
//            case UIEventSubtypeRemoteControlPlay:
//            {
//                NSLog(@"UIEventSubtypeRemoteControlPlay...");
//                break;
//            }
//            case UIEventSubtypeRemoteControlPause:
//            {
//                NSLog(@"UIEventSubtypeRemoteControlPause...");
//                break;
//            }
//            case UIEventSubtypeRemoteControlStop:
//            {
//                NSLog(@"UIEventSubtypeRemoteControlStop...");
//                break;
//            }
//            case UIEventSubtypeRemoteControlNextTrack:
//            {
//                NSLog(@"UIEventSubtypeRemoteControlNextTrack...");
//                break;
//            }
//            case UIEventSubtypeRemoteControlPreviousTrack:
//            {
//                NSLog(@"UIEventSubtypeRemoteControlPreviousTrack...");
//                break;
//            }
//                
//            default:
//                break;
//        }
//    }
//    
//}
//
//- (void)setAudioSession
//{
//    AVAudioSession *session = [AVAudioSession sharedInstance];
//    NSError *setCategoryError = nil;
//    [session setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
//    NSError *activationError = nil;
//    [session setActive:YES error:&activationError];
//}
//
//@end